<template>
	<div class="login">
		<div class="title">自 动 化 测 试 平 台</div>
		<el-form ref="loginRef" :model="LoginFrom" :rules="loginRulues">
			<el-form-item prop="username">
				<el-input v-model="LoginFrom.username" prefix-icon="el-icon-user" placeholder="请输入账户"></el-input>
			</el-form-item>
			<el-form-item prop="password">
				<el-input v-model="LoginFrom.password" type="password" prefix-icon="el-icon-lock" placeholder="请输入密码">
				</el-input>
			</el-form-item>
			<el-form-item label="记住账户">
				<el-switch v-model="status"></el-switch>
			</el-form-item>
			<el-button type="primary" style="width: 100%;" @click="login()">点击登录</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script type="text/javascript">
	export default {
		data() {
			return {
				LoginFrom: {
					username: "",
					password: ""
				},
				status: false,
				// 定义表单校验规则
				loginRulues: {
					username: [{
						required: true,
						message: "请输入账户",
						trigger: 'blur'
					}],
					password: [{
							required: true,
							message: "请输入密码",
							trigger: 'blur'
						},
						{
							min: 6,
							max: 18,
							message: "密码长度为6-18个字符",
							trigger: 'blur'
						}
					]
				}
			}
		},
		methods: {

			login() {
				// 判断是否需要记住账号
				if (this.status) {
					window.localStorage.setItem("username", this.LoginFrom.username)
				} else {
					// 如果勾选不记住账号，则本地删除账户
					window.localStorage.removeItem('username')
				}
				// 对表单进行校验
				this.$refs.loginRef.validate(async res => {
					console.log("表单校验结果:", res)
					// res 为验证的结果，验证通过为true，不通过为false
					if (res) {
						let response = await this.$http.loginApi(this.LoginFrom);
						console.log("响应结果:", response.status)
						// 登录失败
						if (response.status != 200) {
							return this.$message({
								message: "登录失败",
								type: 'error',
								duration: 1000
							});
						}
						
						// 登录成功的处理
						window.sessionStorage.setItem('token', response.data.token)
						window.sessionStorage.setItem("username", this.LoginFrom.username)
						this.$message({
							message: "登录成功",
							type: 'success',
							duration: 1000,
						});
						// 进行页面跳转
						this.$router.push({
							name: "allProject"
						});
					
					}
				});
			}
		},
		mounted() {
			// 判断如果用户点击记住密码，则将账户保存到本地
			if (window.localStorage.getItem("username")) {
				this.LoginFrom.username = window.localStorage.getItem("username")
				this.status = true
			}
		}

	}
</script>

<style type="text/css">
	.login {
		height: 400px;
		width: 600px;
		box-shadow: 0 0 15px #000;
		border-radius: 10px;
		margin: 150px auto;
	}

	.el-form {
		padding: 0 50px;
	}

	.title {
		font: bold 28px/80px "microsoft yahei";
		text-align: center;
		color: #409EFF;

	}
</style>
